package gmu.swe.project.tracker;

import gmu.swe.project.peer.PeerInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;

public class PeerRegistration {

	TrackerUI tUI;
	ArrayList<PeerInfo> peerSet;
	
	public PeerRegistration() {
		peerSet = new ArrayList<PeerInfo>();
	}

	/** Accessors **/
	public ArrayList<PeerInfo> getPeerSet() {
		return peerSet;
	}

	public void setPeerSet(ArrayList<PeerInfo> peerSet) {
		this.peerSet = peerSet;
	}
	
	public void setGUI(TrackerUI ui)
	{
		tUI = ui;
	}
	public void addPeer(PeerInfo peerInfo) {
		//need to remove current data if it's already in the set
		String peerName = peerInfo.getIpAddress();
		Integer peerPort = peerInfo.getPort();
		Iterator<PeerInfo> i = this.peerSet.iterator();
		PeerInfo info = new PeerInfo();
		while(i.hasNext()) {
			info = (PeerInfo) i.next();
			//need to check the IP/port combination so that
			//more than one Peer can run on the same server
			String ip = info.getIpAddress();
			Integer port = info.getPort();
			if(ip.equals(peerName) && port.equals(peerPort)) {
				this.peerSet.remove(info);
				break;
			}
		}
		this.peerSet.add(peerInfo);
		System.out.println("Tracker::PeerRegistrationThread::Registered peer - "+
				info.getIpAddress()+" - with "+
				info.getFiles().size()+" files.");
		tUI.updateTable(peerSet);
	}
	public void removePeer(PeerInfo peerInfo)
	{
		peerSet.remove(peerInfo);
		tUI.updateTable(peerSet);
	}
	public Iterator<PeerInfo> iterator() {
		return this.peerSet.iterator();
	}
	
	/**
	 * Helper method to print the ids and timestamp of all the trackers
	 */
	public void printMe() {
		String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat dfm = new SimpleDateFormat(DATE_FORMAT_NOW);
		Iterator<PeerInfo> i = this.peerSet.iterator();
		System.out.println("PeerRegistration::current size is: "
				+ Integer.toString(this.peerSet.size()));
		while (i.hasNext()) {
			PeerInfo info = (PeerInfo) i.next();
			System.out.println("PeerRegistration::tracker id: "
					+ info.getIpAddress());
			System.out.println("PeerRegistration()::peer # of files: " + info.getFiles().size());
			System.out.println("PeerRegistration::tracker timestamp: "
					+ dfm.format(info.getTimestamp()));

		}
		System.out.println("****************************************");
	}// printMe
}
